<template>
  <ele-toolbar theme="none">
    <div style="display: flex">
      <!--      <div>directorys.length=={{directorys.length}}</div>-->
      <!-- isCommon // 是否公共文件夹  0否，1是-->
      <div v-if="directorys.length>0" class="flex-align-center">
        <el-button
          size="small"
          type="primary"
          class="ele-btn-icon"
          icon="el-icon-upload2"
          @click="openFolderUpload"
        >
          上传
        </el-button>
        <!--<el-button
          size="small"
          type="primary"
          class="ele-btn-icon"
          icon="el-icon-download"
          :disabled="!checked.length"
          @click="downloadFileClick"
        >
          下载
        </el-button>-->
      </div>
      <!-- parentId 代表是根目录 -->
      <!-- v-if="parentId==0"-->
      <!-- directorys.length<=1 则是文件夹 -->
      <el-button
        v-if="directorys.length==0"
        size="small"
        class="ele-btn-icon"
        icon="el-icon-folder-add"
        @click="openFolderAdd"
      >
        新建活动文件夹
      </el-button>

      <el-button
        v-if="directorys.length==0"
        size="small"
        class="ele-btn-icon"
        icon="el-icon-rank"
        @click="videoMovingClick"
        :disabled="!checked.length || checked.length>1"
      >
        <!--只允许选择一个文件夹去视频搬家-->
        视频搬家
      </el-button>


      <el-button
        v-if="directorys.length==0"
        :disabled="!checked.length || checked.length>1"
        size="small"
        type="primary"
        icon="el-icon-share"
        style="margin-left: 10px"
        class="ele-btn-icon hidden-xs-only"
        @click="exportTemplates"
        :loading="loading"
      >
        导出
      </el-button>
      <el-button
        size="small"
        type="danger"
        icon="el-icon-delete"
        style="margin-left: 10px"
        class="ele-btn-icon hidden-xs-only"
        :disabled="!checked.length"
        @click="removeBatch"
      >
        删除
        <!--{{directorys.length}}-->
      </el-button>
      <!-- <el-button
         size="small"
         type="warning"
         icon="el-icon-rank"
         class="ele-btn-icon hidden-xs-only"
         v-if="directorys.length>0 && checked.length>0"
         @click="moveClick"
       >
         移动
       </el-button>-->
    </div>

    <template v-slot:action>
      <!-- 搜索框 -->
      <div
        :class="['ele-file-tool-search', { 'hidden-xs-only': styleResponsive }]"
      >
        <el-input size="small" v-model="search" placeholder="搜索您的文件" @change="changeInput">
          <template v-slot:append>
            <el-button icon="el-icon-search" />
          </template>
        </el-input>
      </div>
      <!-- 显示方式切换 -->
      <i
        v-if="grid"
        class="ele-file-tool-btn el-icon-_menu"
        @click="toggleShowType"
      ></i>
      <i
        v-else
        class="ele-file-tool-btn el-icon-_nav"
        @click="toggleShowType"
      ></i>
    </template>
    <!-- 新建文件夹弹窗 -->
    <folder-add
      ref="folderAdd"
      :directorys="directorys"
      :visible.sync="folderAddVisible"
      :parent-id="parentId"
      @done="onDone"
    />
    <!--视频搬家-->
    <moving-materials
      ref="videoMoving"
      :visible.sync="videoMovingVisible"
      @done="onDone">
    </moving-materials>
    <!-- 上传文件弹窗 -->
    <file-upload
      :visible.sync="folderUpload"
      :points="points"
      :parent-id="parentId"
      @done="onDone"
    />
    <!--移动到-->
    <move-file
      :visible.sync="moveVisible"
      :data="moveData"
      :moveFileAll="moveFileAll"
      :name="moveName"
      @done="onDone"
    ></move-file>
  </ele-toolbar>
</template>

<script>
  import {xlsx} from '../../../../utils/xlsx'
  import {excel} from '../../../../utils/Export2Excel'
  import * as XLSX from 'xlsx';
  import OSS from 'ali-oss';
  import FolderAdd from './folder-add.vue';
  import fileUpload from './file-upload.vue';
  import fileText from './file-text.vue';
  import {getToken} from "../../../../utils/token-util";
  import {
    userOssSignature,
    registerMedia,
    convertAudioScript,
    batchDelete,
    batchTxtDelete,
    batchDeleteFile,
    listUserFiles
  } from '@/api/creatCenter/material';
  import axios from "axios";
  import moveFile from './move-file.vue';
  import MovingMaterials from "@/views/creatCenter/piecemeal/components/moving-materials";
  import {projectQuery} from "@/api/creatCenter/authoringClips";

  import {delProjectjob, delVideoInfo, queryVideos,exportTemplate,exportTemplateCeshi } from "@/api/creatCenter/piecemealManagement";
  import {pageList} from "@/api/agent/pointAllocation";
  import {queryOemPoint} from "@/api/lncomingManagement/cameraManage";




  export default {
    components: {MovingMaterials, FolderAdd,fileUpload,fileText,moveFile },
    props: {
      // 文件夹数据
      directorys: Array,
      // 是否网格展示
      grid: Boolean,
      // 选中数据
      checked: Array,
      // 父级 id
      parentId: Number,
      typeId: Number

    },
    data() {
      return {
        loading:false,
        ossUrl:localStorage.getItem('ossUrl')?localStorage.getItem('ossUrl'):'', //上传图片action
        data:{},
        fileList: [],
        // 搜索关键字
        search: '',
        // 新建文件夹弹窗是否打开
        folderAddVisible: false,
        // ‘视频搬家弹窗’是否打开
        videoMovingVisible:false,
        // 上传成品视频文件弹窗是否打开
        folderUpload:false,
        points:0,//成片扣点点数
        filename:'',

        // 移动文件
        moveVisible:false,
        moveData: null,
        moveFileAll: [],
        moveName:'',
        jsonData:[{
          id:'1',
          name:'小智',
          age:18,
          classes:'商学院'

        },
          {
            id:'2',
            name:'小白',
            age:19,
            classes:'商学院'

          },
          {
            id:'3',
            name:'小蓝',
            age:12,
            classes:'商学院'

          },
          {
            id:'4',
            name:'小花',
            age:14,
            classes:'商学院'

          },
          {
            id:'5',
            name:'小粉',
            age:15,
            classes:'商学院'

          },
          {
            id:'6',
            name:'小黄',
            age:16,
            classes:'商学院'

          },
          {
            id:'7',
            name:'小红',
            age:17,
            classes:'商学院'

          },
          {
            id:'8',
            name:'小黑',
            age:19,
            classes:'商学院'

          },
        ],
        listHander:{
          id:'学号',
          name:'姓名',
          age:'年龄',
          classes:'学院'
        },
        videoListHander:{
          url:''
        }
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    created() {

    },
    methods: {
      /*下载视频 start*/
      downloadFileClick(){

      },
      //单个下载
      downloadFile(row) {

        let name = row.name; //下载的文件名换成自己的

        let url = row.urlSrc;//下载文件的url换成自己的

        let suffix = url.substring(url.lastIndexOf("."), url.length);

        fetch(url)

          .then((res) => res.blob())

          .then((blob) => {

            const a = document.createElement("a");

            const objectUrl = window.URL.createObjectURL(blob);

            a.download = name;

            a.href = objectUrl;

            a.click();

            window.revokeObjectURL(objectUrl);

          });

      },

//批量下载（只需要把多选数组进行循环单个上传方法即可实现）

      batchDownloads() {

        console.log(this.multipleSelection);

        this.multipleSelection.forEach((item) => {

          this.downloadFile(item);

        });

      },
      /*下载 end*/


      uploadClick(file){
        if (file.status !== 'ready') return // 阻止上传成功的触发
        console.log("进入点击事件file=====",file)
        this.selectVideo(file);
        // this.fileList.push(file)
      },
      async selectVideo(fileList){
        console.log(" this.fileList", fileList)
        if(!fileList && !fileList.raw) {
          console.log("请选择文件后提交")
          return
        }
        console.log('组件调用2222================================')
        this.data = await userOssSignature()
        let file = fileList.raw
        console.log(file)
        this.filename = file.name;
        let markIndex = (this.filename).lastIndexOf('.');
        let suffix = this.filename.substring(markIndex)
        let name = this.filename.substring(0, markIndex); // 截取除 .png前的字段名

        let date = new Date().getTime();
        // 构建请求参数
        let param = new FormData()
        param.append("key", this.data.dir + name + '.' + date + suffix)
        param.append("policy", this.data.policy)
        param.append("OSSAccessKeyId", this.data.accessId)
        param.append("success_action_status", '200')
        // param.append("callback",  this.data.callback)     //回调（not)
        param.append("signature", this.data.signature)
        param.append("file", file, file.name)
        param.append('success_action_status', '200')
        let config = {
          headers: {
            'Access-Control-Allow-Origin': '*',
            'x-oss-callback-Authorization': getToken()
          }
        }
        console.log("suffix", suffix)
        axios.post(this.data.host, param, config).then(res => {
          if (res.status == 200) {
            console.log('this.data.host', this.data.host + '/' + name + '.'  + date + suffix)
            let url = this.data.host + '/' + name + '.' + date + suffix;
            let type = file.type;
            console.log('file.type', file.type)
            this.registerMedias(url, type);
            this.onDone();
          } else {
            this.$message.error('上传失败');
          }

        }).catch(err => {
          console.log(err)
        })
      },
      registerMedias(url,type) {
        registerMedia({
          mediaUrl:url,//上传阿里云生成的地址
          mediaType:type,//文件类型
          username:this.$store.state.user.info.username,
          folderId:this.parentId

        })
          .then((data) => {
            this.onDone();
            this.convertAudio(data.data);
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      },
      convertAudio(data){
        let scriptName=this.filename.split('.')[0]+'.txt';
        console.log("scriptName",scriptName)
        convertAudioScript({
          mediaId:data.mediaId,//媒资id
          username:this.$store.state.user.info.username,
          folderId:this.parentId,
          scriptName:scriptName,
          scriptType:2,
          status:0,
          sysMediaId:data.id
        })
          .then((data) => {
            this.$message.success('上传成功');
            this.$refs["upload"].clearFiles()   // 清空上传图片的数据，需要在最后清除，否则文件将无法上传
            loading.close();
            // this.$message.success(data.msg);
            this.onDone();
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.msg);
          });
      },
      //上传事件（未使用）
      uploadClick2(file){
        this.fileList.push(file)
        console.log('this.fileList',this.fileList);
        //非上传到阿里云的，都需要转换为表单传值
        let formdata = new FormData()
        formdata.append('mediaId', '')
        formdata.append('username',  this.$store.state.user.info.username)
        formdata.append('folderId', this.parentId)
        //有台本名称是台本名，直接上传：文件名
        formdata.append('scriptName', this.fileList[0].raw,this.fileList[0].name)
        formdata.append('scriptType', 2)


        //token 白名单
        let token = getToken()
        let config = {
          headers: {
            'Authorization': token
          }
        }
        axios.post('http://localhost/business/montage/script/convertAudioScript', formdata).then(res => {
          console.log(res)
          console.log("res.data",res.data)
        })
      },
      /* 打开上传文件弹窗 */
      openFolderUpload() {
        // 查询oem，发布视频点数
        queryOemPoint({
          id: this.$store.state.user.info.merchantId
        }).then((data) => {
          console.log('发布频点数data',data)
          this.points=data.replyComment // 成片扣点点数
          if(!this.points || this.points<=0){
            this.$message.error("上传视频请先去oem配置成片点数")
            return
          }
          this.folderUpload = true;
        })
          .catch((e) => {
            this.$message.error(e);
          });
        /*pageList({
          oemId:this.$store.state.user.info.oemId
        })
          .then((data) => {
            console.log("data=====",data)
            if(data!=null){
              this.form=data
              this.folderUpload = true;
            }
            else{
              this.$message.error("成片点数未配置，请去oem配置")
            }
          })
          .catch((e) => {
            this.$message.error(e);
          });*/
        console.log("directorys",this.directorys,'parentId',this.parentId)
      },
      /* 打开新建文件夹弹窗 */
      openFolderAdd() {
        this.folderAddVisible = true;
        console.log("directorys============",this.directorys)
        this.$nextTick(()=>{
          this.$refs['folderAdd'].show()
        })
      },

      /*视频搬家*/
      videoMovingClick(){
        /*
        拿到选中的视频文件夹
        this.checked.filter((item, i) => {
          mpList.push(item)
        });*/
        console.log("视频搬家============")
        this.videoMovingVisible = true;
        this.queryVideo(this.checked[0].id)
      },

      async queryVideo(productPolderId) {
        let videoFile=[]
        //根据条件获取所有文件
        let parms={
          username:this.$store.state.user.info.username,
          limit:10,
          page:1,
          productPolderId:productPolderId  // 查看剪辑id下的成片
        }
        videoFile = await queryVideos(parms)
        console.log("查询文件夹下视频个数",videoFile)
        let maxlength=videoFile.count
        this.$nextTick(()=>{
          this.$refs['videoMoving'].show(this.checked[0].id,maxlength)
        })
        console.log("查询的视频=========", videoFile,'this.maxlength',this.maxlength)
      },


      exportTemplates2() {

// multiHeader: 一级表头
// multiHeader2：二级表头
// data：表格数据
// merges：需要合并的单元格
// filename：导出的excel文件名

// console.log("excel",excel)
        /* 方法1 */
        /*this.$sun.export_json_to_excel({
          multiHeader:this.listHander,
          multiHeader2:this.listHander,
          data:this.jsonData,
          merges:'',
          filename: '报表导出一',
        });*/


        /* 方法2 */
        // this.jsonData是要导出的数据内容（表格里的内容），
        // this.listHander对应要导出内容的表头
        // 学生：指向的是excel文件名
        // xlsx(this.jsonData,this.listHander,'学生')



        /* 方法3 */
        /*const data = [
          ['姓名', '年龄'],
          ['Alice', 20],
          ['Bob', 25],
          ['Charlie', 30]
        ];
        const ws = XLSX.utils.aoa_to_sheet(data);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        XLSX.writeFile(wb, 'data.xlsx');*/
      },
      // 导出
      async exportTemplates() {
        this.loading=true
        let videoFile=[]
        //根据条件获取所有文件
        videoFile = await exportTemplate(this.checked[0].id)
        console.log("导出文件夹=========", videoFile)

        let name = this.checked[0].name+'-'+this.$sun.getNowDate()
        console.log("name",name)
        xlsx(videoFile.data,this.videoListHander,name)
        setTimeout(()=>{
          this.loading=false
        },1000)
        // const ws = XLSX.utils.aoa_to_sheet(videoFile.data);
        // const wb = XLSX.utils.book_new();
        // XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        // XLSX.writeFile(wb, 'videoFile.xlsx');
      },

      //搜索文件 回车，或失去焦点
      changeInput(e){
        console.log("搜索文件 回车，或失去焦点e",e,'this.search',this.search)
        this.$emit('search', this.search);
        this.$emit('done');

      },
      /* 批量删除 */
      removeBatch() {
        console.log("删除成功1111this.directorys",this.directorys)
        this.$confirm('确定要删除选中的文件吗?', '提示', {
          type: 'warning'
        })
          .then(() => {
            console.log("this.checked",this.checked,this.checked.map((d) => d.id))
            const loading = this.$messageLoading('请求中..');
            //this.directorys.length =1  为视频
            if(this.directorys.length ==1  ){
              let mpList=[];
              // this.checked. 为选中的所有数据
              /*this.checked.filter((item, i) => {
                mpList.push(item)
              });*/
              delVideoInfo({
                ids:this.checked.map((d) => d.id)
              })
                .then((msg) => {
                  loading.close();
                  this.$message.success('删除成功');
                  this.onDone();
                })
                .catch((e) => {
                  loading.close();
                  this.$message.error(e.msg);
                });
            }
            else{
              // 批量删除文件夹（单个删除通用）
              delProjectjob({
                ids:this.checked.map((d) => d.id)

              })
                .then((msg) => {
                  loading.close();
                  this.$message.success('删除成功');
                  this.onDone();
                })
                .catch((e) => {
                  loading.close();
                  this.$message.error(e.message);
                });
            }
          })
          .catch(() => {
            console.log("删除失败")
          });
      },
      /* 单个/批量移动 */
      moveClick(item){
        console.log("item======", item)
        // checked 代表已选择数据
        // 移动/剪切 文件
        this.moveVisible = true;
        /*
        this.directorys[this.directorys.length - 2]  获取前2个文件夹的内容，-1代表获取上一个文件夹的内容：
        (.name):文件夹名称 （.type)文件夹类型
        */
        this.userFile(this.directorys[this.directorys.length - 2]?.id,item.id)
        this.moveName=this.directorys[this.directorys.length - 2].name;
        this.moveData = this.checked.map((d) => d.id);
        console.log('this.moveData',this.moveData)
        console.log("this.checked===============", this.checked)
      },
      // 查询出可移动的子文件夹
      userFile(parentId,id){
        //用户所创建的文件
        //projectQuery_查询根目录文件夹的接口
        listUserFiles({
          name:this.search,
          // 是否公共文件夹  0否，1是
          isCommon:'',
          //查公共文件根目录不需要传，子级需要
          username: this.$store.state.user.info.username,
          //父级目录：初次传0
          parentId: parentId
        })
          .then((data) => {
            //由于目录只有视频的，使用查询所有
            this.moveFileAll = data
            //获取根目录文件夹
            // this.moveFileAll = await projectQuery(this.form)

            console.log('this.moveFileAll', this.moveFileAll)
          })
          .catch((e) => {
            this.$message.error(e);
          });
      },
      /* 完成刷新列表数据 */
      onDone() {
        this.$emit('done');
      },
      /* 显示方式切换 */
      toggleShowType() {
        this.$emit('update:grid', !this.grid);
      }
    }
  };
</script>

<style lang="scss" scoped>
  /* 图标按钮 */
  .ele-file-tool-btn {
    cursor: pointer;
    font-size: 22px;
    display: inline-block;
    vertical-align: middle;
    margin-left: 10px;
  }

  /* 搜索框 */
  .ele-file-tool-search {
    display: inline-block;
    vertical-align: middle;
    background-color: hsla(0, 0%, 60%, 0.15);
    border-radius: 32px;

    :deep(.el-input-group__append),
    :deep(.el-input__inner) {
      background-color: transparent;
      border: none;
    }

    :deep(.el-input-group__append) {
      padding: 0;
    }

    :deep(.el-input-group__append .el-button) {
      margin: 0;
      padding: 7px 16px 7px 10px;
      border: none;
    }

    :deep(.el-input-group__append .el-button > i) {
      font-size: 16px;
      font-weight: 600;
    }

    :deep(.el-input__inner) {
      width: 200px;
      padding-right: 0;
      box-sizing: border-box;
    }
  }
</style>
